package com.bl.student.service.biz.manager.main.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.enums.UserStatus;
import com.bl.student.common.utils.Generator;
import com.bl.student.dao.model.AdminEntity;
import com.bl.student.dao.redis.AdminInfoDao;
import com.bl.student.dao.redis.model.AdminInfo;
import com.bl.student.service.biz.manager.admin.AdminService;
import com.bl.student.service.biz.manager.main.ManageMainService;
import com.bl.student.service.vo.manager.ManageLoginResponseVo;
import com.bl.student.service.vo.manager.ManageLoginVo;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by yujingyi on 2018/1/22.
 */
@Service
@Log4j2
public class ManageMainServiceImpl implements ManageMainService {

    @Autowired
    AdminService adminService;

    @Autowired
    AdminInfoDao adminInfoDao;

    @Override
    public ManageLoginResponseVo login(ManageLoginVo manageLoginVo) {

        AdminEntity adminEntity = fetchAvailableAdmin(manageLoginVo.getAccount(), manageLoginVo.getPassword());

        String token = Generator.generateAuthCookie(manageLoginVo.getAccount(), manageLoginVo.getPassword());
        AdminInfo adminInfo = new AdminInfo();
        adminInfo.setId(adminEntity.getId() + "");
        adminInfo.setToken(token);
        adminInfo.setAccount(adminEntity.getAccount());
        adminInfo.setLoginTime(System.currentTimeMillis() + "");

        adminInfoDao.setAdminInfo(token, adminInfo);

        ManageLoginResponseVo manageLoginResponseVo = ManageLoginResponseVo.builder()
                .id(adminEntity.getId())
                .account(adminEntity.getAccount())
                .token(token)
                .build();

        return manageLoginResponseVo;
    }

    private AdminEntity fetchAvailableAdmin(String account, String password) {
        AdminEntity adminEntity = adminService.getAdminByAccount(account);

        if (adminEntity == null) {
            throw new CommonServiceException(ApiResponseCode.USER_NOT_EXIST.getCode(), ApiResponseCode.USER_NOT_EXIST.getMsg());
        }

        if (!adminEntity.getPassword().equals(password)) {
            throw new CommonServiceException(ApiResponseCode.PASSWORD_WRONG.getCode(), ApiResponseCode.PASSWORD_WRONG.getMsg());
        }
        
        return adminEntity;
    }

    @Override
    public void logout(String token) {
        adminInfoDao.delAdminInfo(token);
    }
}
